package com.fizzkai.p2p.core.service.impl;

import com.fizzkai.p2p.core.VerifyCodeVo;
import com.fizzkai.p2p.core.exception.DisplayableException;
import com.fizzkai.p2p.core.service.IVerifyCodeService;
import com.fizzkai.p2p.core.util.Constants;
import com.fizzkai.p2p.core.util.DateUtil;
import com.fizzkai.p2p.core.util.UserContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StreamUtils;

import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {


    @Value("${msg.url}")
    private String url;
    @Value("${msg.loc}")
    private String loc;
    @Value("${msg.userid}")
    private String userid;
    @Value("${msg.appkey}")
    private String appkey;


    @Override
    public void sendVerifyCodeCode(String phoneNumber) {
        // 0. 隔离 发送过验证码的 session
        VerifyCodeVo vo = UserContext.getVerifyCodeVo();
        // 0.1 已发送 验证码的 情况
        if (vo != null && DateUtil.getTimeBetween(vo.getSendTime(), new Date()) < 90) {
            throw new DisplayableException("发送验证码太频繁了，请稍后再试！");
        }

        // 1. 生成验证码
        String randomCode = UUID.randomUUID().toString().substring(0, 4);
        // 2. 执行短信发送，
        String pattern = "这是您的验证码：{0}，有效时间为 {1} 分钟，请尽快使用！";
        String msg = MessageFormat.format(pattern, randomCode, Constants.VERIFYCODE_VALID_TIME);
        // 2.1 发送 短息 TODO there is no Doubt that
        try {
            sendRealMsg(msg);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        System.out.println(msg);
        // 3. 记录 VerifyCodeVo 进 Session
        VerifyCodeVo codeVo = new VerifyCodeVo();
        codeVo.setPhoneNumber(phoneNumber);
        codeVo.setRandomCode(randomCode);
        codeVo.setSendTime(new Date());
        UserContext.setVerifyCodeVo(codeVo);
    }

    @Override
    public boolean validate(String username, String verifycode) {
        VerifyCodeVo vo = UserContext.getVerifyCodeVo();
        return vo != null
            // 手机号码相等
            && vo.getPhoneNumber().equals(username)
            // 验证码相等
            && vo.getRandomCode().equalsIgnoreCase(verifycode)
            // 短信在 有效期之内
            && DateUtil.getTimeBetween(vo.getSendTime(), new Date()) <= Constants.VERIFYCODE_VALID_TIME * 60;
    }

    public String sendRealMsg(String msg) throws Exception {
        URL url = new URL("https://way.jd.com/turing/turing");
        // 建立连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 设置请求的 方式
        conn.setRequestMethod("GET");
        // 设置需要 拼接的 参数
        StringBuilder str = new StringBuilder(50)
            .append("info=").append(msg)
            .append("&loc=").append(loc)
            .append("&userid=").append(userid)
            .append("&appkey=").append(appkey);
        // 我们需要 输出内容，默认值是 false ,表示 没有 参数 输出
        conn.setDoOutput(true);
//         设置 输出 内容
        conn.getOutputStream().write(str.toString().getBytes("UTF-8"));
        // 请求连接
        conn.connect();
        // 打印响应
        String res = StreamUtils.copyToString(conn.getInputStream(), Charset.forName("UTF-8"));
        return res;
    }
}
